from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework import generics, mixins, viewsets
from rest_framework.decorators import action
from rest_framework.generics import ListAPIView, RetrieveAPIView, CreateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from articles.utils import PageNum
from spit.models import Spit
from spit.serializers import SpitLisModelSerializer


class SpitListAPIView(ModelViewSet):
    #获取所有吐槽及吐槽详情和发布吐槽
    queryset = Spit.objects.all()
    serializer_class = SpitLisModelSerializer
    def create(self, request, *args, **kwargs):
        content = request.data.get('content')
        parent = request.data.get('parent')
        user = request.user
        if parent == None or not parent:
            try:
                 new_spit = Spit.objects.create(content=content)
            except Exception as e:

                return Response({'msg': 'error'})
            return Response({
                'id':new_spit.id,
                'content':new_spit.content,
                'publishtime':new_spit.publishtime,
                'uesrid':'null',
                'nickname':new_spit.nickname,
                'visits':new_spit.visits,
                'thumbup':new_spit.thumbup,
                'share':0,
                'comment':new_spit.comment,
                'state':0,
                'avatar':new_spit.avatar,
                'collected':new_spit.collected,
                'hasthumbup':new_spit.hasthumbup,
                'parent':new_spit.parent
            })

        else:

            try:
                spit = Spit.objects.get(id=int(parent))

            except Exception as e:
                return Response({'msg': 'error'})
            try:
                new_spit=Spit.objects.create(userid=user.id,content=content,parent=spit)
            except Exception as e:
                return Response({'msg': 'error'})
            spit.visits+=1
            spit.comment+=1
            spit.save()
            return Response({
                'id':new_spit.id,
                'content':new_spit.content,
                'publishtime':new_spit.publishtime,
                'uesrid':'null',
                'nickname':new_spit.nickname,
                'visits':new_spit.visits,
                'thumbup':new_spit.thumbup,
                'share':0,
                'comment':new_spit.comment,
                'state':0,
                'avatar':new_spit.avatar,
                'collected':new_spit.collected,
                'hasthumbup':new_spit.hasthumbup,
                'parent':'null'
            })


class SpitCollectView(RetrieveAPIView):
    # 收藏或取消收藏
    queryset = Spit.objects.all()
    serializer_class = SpitLisModelSerializer
    lookup_field = 'id'
    def put(self,request,id):
        user = request.user
        conn = get_redis_connection('question')
        flag = conn.hget("collect%s" % user.id, id)
        spit = self.get_object()
        if not flag or flag.decode() == 'false':
            spit.visits += 1
            spit.save()
            conn.hset("collect%s" % user.id, id, 'true')
            return Response({"message": "收藏成功", "success": "true"})
        else:
            conn.hset("collect%s" % user.id, id, 'false')
            return Response({"message": "取消收藏成功", "success": "true"})

class AddthumbupView(RetrieveAPIView):
#点赞或取消点赞
    queryset = Spit.objects.all()
    serializer_class = SpitLisModelSerializer
    lookup_field = 'id'
    def put(self,request,id):
        spit = self.get_object()
        if spit.hasthumbup == False:
            spit.thumbup += 1
            spit.hasthumbup=True
            spit.save()
            return Response({"message": "点赞成功", "success": "true"})
        else:
            if spit.thumbup >= 1:
                spit.thumbup -= 1
                spit.save()
            spit.hasthumbup = False
            spit.save()
            return Response({"message": "取消点赞成功", "success": "true"})

class SpitcommentView(ListAPIView):
    #获取吐槽评论
    serializer_class = SpitLisModelSerializer
    lookup_field = 'id'
    def get_queryset(self):
        id=self.kwargs['id']
        if id:
            spit = Spit.objects.get(id=id)
            spits=Spit.objects.filter(parent=spit)
            if spits:
                return spits
            return None
        else:
            None


